package com.cyf.plc.ui.fragment

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.graphics.Typeface
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.cyf.library.util.logi
import com.cyf.plc.R
import com.cyf.plc.adapter.RoomDarkAdapter
import com.cyf.plc.base.BaseFragment
import com.cyf.plc.bean.*
import com.cyf.plc.constant.Constants
import com.cyf.plc.data.remote.WeatherService
import com.cyf.plc.databinding.FragmentDarkMainBinding
import com.cyf.plc.model.PlcRoom
import com.cyf.plc.plc.PlcExecutor
import com.cyf.plc.ui.SettingActivity
import com.cyf.plc.util.State
import com.cyf.plc.util.setValueText
import com.cyf.plc.util.showToast
import com.cyf.plc.viewmodel.MainViewModel
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Author：Lei on 2021/2/7
 */
@ExperimentalCoroutinesApi
class MainDarkFragment : BaseFragment<MainViewModel, FragmentDarkMainBinding>() {


    override fun layoutId(): Int {
        return R.layout.fragment_dark_main
    }

    var selectPanelIndex = 0
    var plcRoomList = ArrayList<PlcRoom>()
    override fun initView() {
        mViewBinding.recyclerView.layoutManager = LinearLayoutManager(
            activity,
            LinearLayoutManager.HORIZONTAL, false
        )
//        plcRoomList.add(PlcRoom(1,"客厅",1,true))
//        plcRoomList.add(PlcRoom(2,"餐厅",1))
//        plcRoomList.add(PlcRoom(3,"卧室",1))
//        plcRoomList.add(PlcRoom(4,"主卧",1))
//        plcRoomList.add(PlcRoom(5,"次卧",1))
//        plcRoomList.add(PlcRoom(6,"书房",1))
        mViewBinding.recyclerView.adapter =
            RoomDarkAdapter(plcRoomList, activity, RoomDarkAdapter.OnItemClickListener {
                selectPanelIndex = it
                updatePanel(panelMap[selectPanelIndex])
            })

        initClick()
        //初始化故障点位
        getSystemFaultAttributes()
        var sourceHanSansCN = Typeface.createFromAsset(activity?.getAssets(), "fonts/BebasNenu.ttf")
        mViewBinding.tvShowTemp.typeface = sourceHanSansCN
        mViewBinding.tvPanelHumidity.typeface = sourceHanSansCN
        mViewBinding.tvPanelSetTemp.typeface = sourceHanSansCN
        mViewBinding.tvPanelTemp.typeface = sourceHanSansCN
    }

    var powerOn = false
    var outHome = false
    var energyConservation = false
    var windLow = false
    var panelMap = HashMap<Int, PanelStatus>()
    var panelSwitchOn = false
    var setTemp = 20
    fun initClick() {
        mViewBinding.llTalk.setOnClickListener {
            val launchIntent = requireActivity().packageManager.getLaunchIntentForPackage("com.dnake.talk")
            launchIntent?.let { startActivity(it) }
        }
        mViewBinding.llSmart.setOnClickListener {
            showToast("功能规划中，敬请期待...")
        }
        //设置
        mViewBinding.ivSetting.setOnClickListener {
            startActivity(Intent(this.context, SettingActivity::class.java))
        }
        //制冷
        mViewBinding.ivCold.setOnClickListener {
            handleSystemMode(Constants.MODE_COLD)
        }
        //制热
        mViewBinding.ivHot.setOnClickListener {
            handleSystemMode(Constants.MODE_HOT)
        }
        //通风
        mViewBinding.ivWind.setOnClickListener {
            handleSystemMode(Constants.MODE_WIND)
        }
        //除湿
        mViewBinding.ivArefaction.setOnClickListener {
            handleSystemMode(Constants.MODE_CHUSHI)
        }
        //系统开关
        mViewBinding.ivPower.setOnClickListener {
            var plcWriteAttribute = PlcWriteAttribute(
                Constants.SYSTEM_POWER_ID,
                if (powerOn) Constants.POWER_OFF else Constants.POWER_ON,
                Constants.VW
            )
            PlcExecutor.write(plcWriteAttribute)
        }
        //离家
        mViewBinding.ivOutHome.setOnClickListener {
            var plcWriteAttribute = PlcWriteAttribute(
                Constants.SYSTEM_OUT_HOME_ID,
                if (outHome) Constants.POWER_OFF else Constants.POWER_ON,
                Constants.VW
            )
            PlcExecutor.write(plcWriteAttribute)
        }
        //节能
        mViewBinding.ivEnergyConservation.setOnClickListener {
            var plcWriteAttribute = PlcWriteAttribute(
                Constants.SYSTEM_ENERGY_CONSERVATION_ID,
                if (energyConservation) Constants.POWER_OFF else Constants.POWER_ON,
                Constants.VW
            )
            PlcExecutor.write(plcWriteAttribute)
        }
        //风量
        mViewBinding.ivWindSpeed.setOnClickListener {
            var plcWriteAttribute = PlcWriteAttribute(
                Constants.SYSTEM_WIND_ID,
                if (windLow) Constants.WIND_HIGH else Constants.WIND_LOW,
                Constants.VW
            )
            PlcExecutor.write(plcWriteAttribute)
        }
        //面板开关、设定温度
        mViewBinding.ivPanelSwitch.setOnClickListener {
            var plcWriteAttribute = PlcWriteAttribute(
                Constants.PANEL_SWITCH_ID + Constants.PANEL_TEMP_LENGTH * selectPanelIndex,
                if (panelSwitchOn) Constants.POWER_OFF else Constants.POWER_ON,
                Constants.VW
            )
            PlcExecutor.write(plcWriteAttribute)
        }
        mViewBinding.ivTempMinus.setOnClickListener {
            var plcWriteAttribute = PlcWriteAttribute(
                Constants.PANEL_SET_TEMP_ID + Constants.PANEL_TEMP_LENGTH * selectPanelIndex,
                (--setTemp) * 10f,
                Constants.VW
            )
            PlcExecutor.write(plcWriteAttribute)
        }
        mViewBinding.ivTempPlus.setOnClickListener {
            var plcWriteAttribute = PlcWriteAttribute(
                Constants.PANEL_SET_TEMP_ID + Constants.PANEL_TEMP_LENGTH * selectPanelIndex,
                (++setTemp) * 10f,
                Constants.VW
            )
            PlcExecutor.write(plcWriteAttribute)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateSystem(systemStatus: SystemStatus) {
        systemStatus.toString().logi("MainDarkFragment")
        WeatherService.GET_WEATHER_URL_OPEN_API.logi("MainDarkFragment")
        setValueText(systemStatus.temp, mViewBinding.tvShowTemp, "℃")
//        mViewBinding.systemStatus = SystemStatus("20","45",1f,1f,25f,true,true,"1",1f,1f,true,true)
        mViewBinding.systemStatus = systemStatus
        powerOn = systemStatus.power
        outHome = systemStatus.leaveHome
        energyConservation = systemStatus.energyConservation
        windLow = (systemStatus.volumeValue == Constants.WIND_LOW)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updatePanelList(panelHashMap: HashMap<Int, PanelStatus>) {
        panelMap = panelHashMap
        var panelStatus = panelHashMap[selectPanelIndex]
        updatePanel(panelStatus)
    }

    var deviceBean: DeviceBean = DeviceBean("000000000000")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateFloorRoomInfo(deviceBean: DeviceBean) {
        if (this.deviceBean.deviceId.equals(deviceBean.deviceId)) {
            return
        }
        // 创建/获取一个sp文件
        val sharedPref = context?.getSharedPreferences("RoomList", Context.MODE_PRIVATE)
        var json = sharedPref?.getString("plc_room","")
        if (!json.isNullOrEmpty()){
            val log = "获取本地:" + json
            log.logi()
            plcRoomList.clear()
            val parameterizedType = Types.newParameterizedType(List::class.java, PlcRoom::class.java)
            var  temp = moshi.adapter<List<PlcRoom>>(parameterizedType)
                .fromJson(json)
            temp?.forEach {
                plcRoomList.add(it)
            }
            PlcExecutor.roomSize = plcRoomList.size
            (mViewBinding.recyclerView.adapter as RoomDarkAdapter).notifyDataSetChanged()
            return
        }
        this.deviceBean = deviceBean
        deviceBean.deviceId?.let {
            mViewModel.requestYunConfig(it)
                .observe(viewLifecycleOwner, Observer { state ->
                    //获取到配置啦
                    when (state) {
                        is State.Success -> {
                            val log = "获取配置成功:" + state.data
                            log.logi()
                            val response: FloorRoomResponse = state.data
                            var dataBeanList = response.data
                            if (!dataBeanList.isNullOrEmpty()) {
                                plcRoomList.clear()
                                for (dataBean in dataBeanList) {
                                    val pos = dataBeanList.indexOf(dataBean)
                                    val floorId = pos + 1
                                    for (pannel in dataBean.pannelList!!){
                                        val roomId = pannel.order?.toInt()
                                        val plcRoom = PlcRoom(
                                            roomId?.minus(1),
                                            pannel.name,
                                            floorId.toLong()
                                        )
                                        plcRoomList.add(plcRoom)
                                    }
                                }
                                plcRoomList[0].roomSelect = true
                                val parameterizedType = Types.newParameterizedType(List::class.java, PlcRoom::class.java)
                                var toJson = moshi.adapter<List<PlcRoom>>(parameterizedType)
                                    .toJson(plcRoomList)
                                sharedPref?.edit()?.putString("plc_room",toJson)?.apply()
                                PlcExecutor.roomSize = plcRoomList.size
                                (mViewBinding.recyclerView.adapter as RoomDarkAdapter).notifyDataSetChanged()
                            }
                        }
                    }
                })
        }
    }

    fun handleSystemMode(systemMode: Float) {
        if (powerOn) {
            showToast("开机不能切模式！")
            return
        }
        var plcWriteAttribute =
            PlcWriteAttribute(Constants.SYSTEM_MODE_ID, systemMode, Constants.VW)
        PlcExecutor.write(plcWriteAttribute)
    }

    override fun createViewModel(): MainViewModel = activity?.run {
        ViewModelProvider(this)[MainViewModel::class.java]
    } ?: throw Exception("Invalid Activity")

    override fun onStart() {
        super.onStart()
        mViewBinding.timeView.start()
        PlcExecutor.updatePlcSystem()
    }

    override fun onStop() {
        super.onStop()
        mViewBinding.timeView.stop()
    }

    fun updatePanel(panelStatus: PanelStatus?) {
        if (panelStatus != null) {
            panelStatus.toString().logi("MainDarkFragment")
            setValueText(panelStatus.temp.toString(), mViewBinding.tvPanelTemp, "℃")
            setValueText(panelStatus.humidity.toString(), mViewBinding.tvPanelHumidity, "%")
            setValueText(panelStatus.setTemp.toString(), mViewBinding.tvPanelSetTemp, "℃")
            panelSwitchOn = panelStatus.power
            setTemp = panelStatus.setTemp
            mViewBinding.ivPanelSwitch.setImageResource(if (panelStatus.power) R.drawable.img_21_panel_on else R.drawable.img_21_panel_off)
        }
    }

    private fun getSystemFaultAttributes() {
        mViewModel.getAllPlcFaultAddress().observe(viewLifecycleOwner, Observer {
            PlcExecutor.plcFaultList = it
        })
    }
}